import React, { PureComponent, Fragment } from 'react'
import { connect } from "react-redux";

import { Layout } from 'antd';
import {
    PageHeader,
    Table,
    ButtonEvent,
    Modal,
    Form,
    Tip,
    SearchForm,
} from '../../../components';
import { mainService } from '../../../service';
import { cmsFormAction as actionCreates, mainAction } from '../../../store/action';

const breadcrumbList = [{
    title: '模块管理'
}, {
    title: '表单管理'
}];
const searchdata = [
    {type:'input',title:'表单名',name:'like__name',value:'',placeholder:"请输入广告位名称"}
];

class Index extends PureComponent{
    state = {
        //api名称
        apiname:'cms/form',
        visible:false,
        modalTitle:"表单",
        //设置表单按钮
        tableBtn:[
            {key:1,type:'primary',value:'添加',onClick:()=>{ this.openModel('add'); }},
            {key:2,type:'danger',value:'删除',onClick:()=>{ this.openModel('del'); }}
        ],
        //表格colums
        columns:[
            {title: 'ID',dataIndex: 'id',width:100}
            ,{title: '表单名',dataIndex: 'name',width:300}
            ,{title: '调用/数据',key: 'operation2',width:200,render: (value) =><ButtonEvent data={ [
                {key:1,type:'primary',value:'数据列表',size:'small',onClick:()=>{
                    this.listpage(value)
                }}
            ]}/> }
            ,{title: '描述',dataIndex: 'description',width:300,onCell: () =>{ return {style: {whiteSpace: 'nowrap',maxWidth: 500}} }}
            ,{ title: '操作', key: 'operation',fixed:'right', width:200, render: (value) =><ButtonEvent data={ [
                {key:3,type:'primary',value:'配置字段',size:'small',onClick:()=>{
                    this.setfield(value)
                }}
                ,{key:1,value:'修改',size:'small',onClick:()=>{
                    this.editModel(value)
                }}
                ,{key:2,type:'danger',value:'删除',size:'small',onClick:()=>{
                    this.delModel(value)
                }}
            ]}/> }
        ],
        //form表单
        inputdata : [],
        footerbar:null,
        footBar:[],

        //选中数据
        selectedRowKeys:[],
        selectedRows:[],
        selectedIds:[],
        pagination : {
            current:1,
            onShowSizeChange:(cur,pageSize)=>{this.changeRowsPage(cur,pageSize)},
        },

    }

    render(){
        const { loading, list, emptyText, total, pageSize, page } = this.props;
        const { tableBtn, columns, visible, modalTitle, inputdata, footerbar, pagination, selectedRowKeys } = this.state;
        pagination.total = total;
        pagination.current = page;
        pagination.pageSize=pageSize;
        const locale = {
            emptyText
        }
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange
        }
        const action = <ButtonEvent data={ [
            {key:1,type:'primary',value:'刷新',size:'small',onClick:()=>{
                this.reset()
            }}
        ]}/>;

        return(
            <Fragment>
                <PageHeader title={breadcrumbList[1]['title']} breadcrumbList={breadcrumbList} action={action}></PageHeader>

                <Layout.Content style={{margin:'24px',padding:'24px 32px 8px',backgroundColor:'#fff'}}>
                    <SearchForm
                        style={{ marginBottom: 16 }}
                        layout = 'inline'
                        data={searchdata}
                        reset={this.reset}
                        submit={this.search}
                        wrappedComponentRef={(form) => this.searchRef = form}
                    />

                    <ButtonEvent
                        data={ tableBtn }
                        style={{marginBottom:16}}
                    />
                    <Table
                        columns = {columns}
                        dataSource = { list }
                        locale = {locale}
                        loading = { loading }
                        rowSelection={ rowSelection }
                        onChange = { this.handleChange }
                        pagination ={ pagination }
                    />
                </Layout.Content>

                <Modal
                    visible={visible}
                    title = {modalTitle}
                    onCancel={this.handleCancel}
                    maskClosable={false}
                    footer={ footerbar }
                    destroyOnClose={true}
                    drag={true}
                    className="modal-top"
                >
                    <Form
                        layout = 'horizontal'
                        data = {inputdata}
                        wrappedComponentRef={(form) => this.formRef = form}
                    />
                </Modal>
            </Fragment>
        )
    }
    
    //查询数据
    search = (name)=>{
        const { bindLoading, bindPage, pageSize } = this.props;
        bindLoading(true)
        this.loadList({page:1,rows:pageSize,...name})
        bindPage(1);
    }
    //重置查询
    reset = () => {
        const { bindLoading, pageSize, page } = this.props;
        bindLoading(true)
        this.loadList({page,rows:pageSize})
    }
    //关闭弹窗
    handleCancel=()=>{
        this.setState({
            visible:false
        })
    }
    //排序和翻页
    handleChange = (pagination, filters, sorter)=>{
        const { bindLoading } = this.props;
        let values = this.searchRef.getItemsValue();
        let order={};
        if(Object.keys(sorter).length>0){
            order={
                field:sorter.field,
                order:sorter.order==="descend" ? 'desc':'asc'
            }
        }
        bindLoading(true)
        this.loadList({page:pagination.current,rows:pagination.pageSize,...order,...values})
    }
    //每页条数
    changeRowsPage = (cur,pagesize)=>{
        const { bindPageSize } = this.props;
        bindPageSize(pagesize);
    }
    //选择
    onSelectChange=(selectedRowKeys, selectedRows) => {
        let newselectedRows=[];
        let selectedIds=[];
        for (let i = 0; i < selectedRows.length; i++) {
            newselectedRows.push(selectedRows[i]);
            selectedIds.push(selectedRows[i].id);
        }
        this.setState({ 
            selectedRowKeys,
            selectedRows:newselectedRows,
            selectedIds
        });
    }
    //保存按钮状态
    changeBtnLoading = (bool)=>{
        this.props.bindBtnLoading(bool)
    }
    //获取列表
    loadList = async (data)=>{
        const { bindList, bindPage } = this.props;
        const { apiname } = this.state;
        let res = await mainService.getlist(apiname,data);

        bindList(res);
        bindPage(data.page);
    }

    //消息提示
    tipMsg = (res,type='')=>{
        const { bindLoading, bindPage, pageSize, page } = this.props;
        if(res.code===0){
            this.handleCancel();
            Tip.Message(res.msg,'success');
            bindLoading(true);

            if(type==='del'){
                this.loadList({page:1,rows:pageSize})
                bindPage(1);
            }else{
                this.loadList({page,rows:pageSize})
            }
        }else{
            Tip.Message(res.msg,'error')
        }
    }

    /**
     * 按钮工具操作
     */
    //openModel
    openModel=(type)=>{
        const { selectedIds } = this.state;
        switch (type) {
            case 'add':
            
                this.setState({
                    modalTitle:'添加广告位'
                });
                this.addFormJsx();
                break;
            case 'del':
                if(selectedIds.length > 0){
                    this.delete(selectedIds);
                }else{
                    Tip.Message('至少选择一条数据进行删除','error')
                }
                break;
            default:
                break;
        }
    }
    editModel = (obj)=>{
        this.setState({
            modalTitle:'修改广告位'
        });
        this.editFormJsx(obj);
    }
    delModel = (obj)=>{
        let id=[];
        id.push(obj.id)
        this.delete(id);
    }

    listpage = (obj)=>{
        const { apiname } = this.state;
        const { history } = this.props;
        history.replace('/'+apiname+"/list?id="+obj.id);
    }
    setfield = (obj)=>{
        const { apiname } = this.state;
        const { history } = this.props;
        history.replace('/'+apiname+"/set?id="+obj.id);
    }

    //保存数据
    save = async (type)=>{
        const { apiname } = this.state;
        this.changeBtnLoading(true);
        let values = await this.formRef.getItemsValue();
        if(values){
            try{
                let res = await mainService.crud(apiname+"/"+type,values);
                this.tipMsg(res);
            }catch{
                this.tipMsg({code:3,msg:"网络错误"});
            }
        }
        setTimeout(()=>{
            this.changeBtnLoading(false);
        },500);
    }
    delete = (arr)=>{
        const { apiname } = this.state;
        Tip.Modal('您真的要删除?','confirm',{
            onOk:async ()=>{
                let res = await mainService.crud(apiname+"/del",arr);
                this.tipMsg(res,'del');
            }
        })
    }

    selectChange = (e)=>{
        const { formData } = this.props;
        const { inputdata } = this.state;
        //初始化添加的form表单数据
        let formDataArr=[];
        switch (e) {
            case "text":
                for (let i=0;i<formData['arr'].length;i++) {
                    let v = formData['arr'][i];
                    let o = {};
                    o = Object.assign({},formData[v]);
                    if(v==='type'){
                        o.onChange=this.selectChange
                    }
                    if(v==='width' || v ==='height'){
                        o.type="input.hidden";
                        o.value = 0;
                    }
                    formDataArr.push(o)
                }
                break;
            case "banner":
                for (let i=0;i<formData['arr'].length;i++) {
                    let v = formData['arr'][i];
                    let o = {};
                    o = Object.assign({},formData[v]);
                    if(v==='type'){
                        o.onChange=this.selectChange
                    }
                    formDataArr.push(o)
                }
                break;
            default:
                break;
        }
        for(let i=0;i<inputdata.length;i++){
            if(formDataArr[i]===undefined){
                formDataArr[i]=inputdata[i]
            }else{
                if(formDataArr[i].value===undefined){
                    formDataArr[i].value=inputdata[i].value
                }
            }
        }
        this.setState({
            inputdata:formDataArr
        });
    }
    //form 表单生成
    addFormJsx=()=>{
        const { formData } = this.props;
        //初始化添加的form表单数据
        let formDataArr=[];
        for (let i=0;i<formData['arr'].length;i++) {
            let v = formData['arr'][i];
            let o = {};
            o = Object.assign({},formData[v]);
            if(v === "type"){
                o.onChange=this.selectChange
            }
            formDataArr.push(o)
        }
        this.setState({
            inputdata:formDataArr,
            visible:true,
            footerbar:
            <ButtonEvent data={[
                {key:1,value:'取消',onClick:this.handleCancel},
                {key:2,type:'primary',value:'保存',btnloading:"1",onClick:()=>{
                    this.save('add')
                }}
            ]}/>
        });
    }
    //编辑数据
    editFormJsx = (obj)=>{
        const { formData } = this.props;
        //初始化添加的form表单数据
        let formDataArr=[];
        for (let i=0;i<formData['arr'].length;i++) {
            let v = formData['arr'][i];
            let o = {};
            o = Object.assign({},formData[v]);
            if(v === "type"){
                o.onChange=this.selectChange
            }
            if(obj['type']==="text"){
                if(v==='width' || v ==='height'){
                    o.type="input.hidden";
                    o.value=0;
                }
            }
            o.value = obj[v];
            formDataArr.push(o)
        }

        let id = {type:'input.hidden',title:'ID',name:'id',value:obj['id'],disabled:true};
        formDataArr.push(id);
        this.setState({
            inputdata:formDataArr,
            visible:true,
            footerbar:
            <ButtonEvent data={ [
                {key:1,value:'取消',onClick:this.handleCancel},
                {key:2,type:'primary',value:'保存',btnloading:"1",onClick:()=>{
                    this.save('edit')
                }}
            ]}/>
        });
    }

    componentDidMount(){
        const { pageSize, page } = this.props;
        this.loadList({page,rows:pageSize});
    }
}

const mapStateToProps = (state)=>{
    const name = 'cms_form';
    const list = state.getIn([name,'list']).toJS();
    const loading = state.getIn([name,'loading']);
    const total = state.getIn([name,'total'])
    const formData = state.getIn([name,'formData']).toJS();
    const emptyText = state.getIn([name,'emptyText']);
    
    const page = state.getIn([name,'page']);
    const pageSize = state.getIn([name,'pageSize']);

    const btnloading = state.getIn(['main','btnloading']);

    return{
        list,
        loading,
        total,
        formData,
        emptyText,

        page,
        pageSize,
        btnloading
    }
}
const mapDispatchToProps = (dispatch)=>{
    return{
        bindLoading(loading){
            dispatch(actionCreates.setLoading(loading))
        },
        bindPageSize(pageSize){
            dispatch(actionCreates.setPagesize(pageSize));
        },
        bindPage(page){
            dispatch(actionCreates.setPage(page));
        },
        bindList(res){
            if(res.code === 0){
                let list=res.data;
                dispatch(actionCreates.getList(list.rows,list.total));
            }else{
                dispatch(actionCreates.setEmptyText(res.msg));
            }
            dispatch(actionCreates.setLoading(false));
        },
        bindBtnLoading(bool){
            dispatch(mainAction.setBtnLoading(bool));
        }
    }
}
export default connect(mapStateToProps,mapDispatchToProps)(Index);